<script setup>
import { ref, reactive } from 'vue'
import { useMessage } from 'naive-ui'
import { Send, Refresh, Copy } from '@vicons/ionicons5'

const message = useMessage()
const emit = defineEmits(['message'])

// 表单数据
const formData = reactive({
  orderNo: '',
  environment: 'uat', // 默认选择UAT环境
  testType: 'order' // 新增：测试类型，默认为order
})

// 环境配置
const environments = [
  { label: 'UAT环境', value: 'uat', url: 'https://cnapp-uat.sgs.net/gpo-micro-api/ai/tool/update' },
  { label: 'Prod环境', value: 'prod', url: 'https://cnapp.sgs.net/gpo-micro-api/ai/tool/update' }
]

// 测试类型配置
const testTypes = [
  { label: 'Order更新测试', value: 'order' },
  { label: 'Enquiry更新测试', value: 'enquiry' }
]

// 请求参数模板
const defaultOrderRequestData = {
  "objectNo": "",
  "objectType": "order",
  "productLineCode": "HL",
  "applicant": {
    "contactName": "邬小姐applicant",
    "email": "zhangkerui@echom.com",
    "fax": "6666",
    "telephone": "+86 20 32200917",
    "mobile": "86 13544588122"
  },
  "payer": {
    "contactName": "张可锐payer",
    "email": "payerzhangkerui@echom.com",
    "fax": "payer444444",
    "telephone": "+86 20 32200918",
    "mobile": "666666"
  },
  "buyer": {
    "contactName": "张可锐buyer",
    "email": "zhangkerui@echom.com",
    "fax": "buyer444444",
    "telephone": "+86 20 32200916",
    "mobile": "333"
  },
  "agent": {
    "customerNameCn": "agentCustomerNameCn",
    "customerNameEn": "agentCustomerNameEn",
    "addressCn": "agentAddressCn",
    "addressEn": "agentAddressEn",
    "contactName": "agent张可锐",
    "email": "agentzhangkerui@echom.com",
    "fax": "agent444444",
    "telephone": "+86 20 32200919",
    "mobile": "111"
  },
  "supplier": {
    "customerNameCn": "supplierCustomerNameCn",
    "customerNameEn": "suppliercustomerNameEn",
    "addressCn": "supplieraddressCn",
    "addressEn": "supplieraddressEn",
    "contactName": "supplier张可锐",
    "email": "supplierzhangkerui@echom.com",
    "fax": "supplier87777",
    "telephone": "+86 20 32200917",
    "mobile": "5555"
  },
  "manufacturer": {
    "customerNameCn": "manufacturercustomerNameCn",
    "customerNameEn": "manufacturercustomerNameEn",
    "addressCn": "manufactureraddressCn",
    "addressEn": "manufactureraddressEn",
    "contactName": "manufacturer张可锐",
    "email": "manufacturerzhangkerui@echom.com",
    "fax": "manufacturer444444",
    "telephone": "+86 20 322009188",
    "mobile": "manufacturer333"
  },
  "reportInfo": {
    "sameAsApplicant": 0,
    "reportLanguage": "1",
    "reportHeaderEn": "GUANGZHOU XIYIN SUPPLY CHAIN MANAGEMENT CO., LTD8888",
    "reportHeaderCn": "广州希音供应链管理有限公司888ai",
    "reportAddressEn": "111111111111111111111111111111ai",
    "reportAddressCn": "广州市番禺区南村镇南草堂金坑广兴红棉路6号2栋102、201888888"
  },
  "serviceRequirement": {
    "contactInfos": [
      {
        "contactsType": "invoiceDeliverTo",
        "deliverOthers": "intest@.com",
        "deliverTo": ["applicant", "buyer"]
      },
      {
        "contactsType": "softCopyDeliverTo",
        "deliverOthers": "sftest@.com",
        "deliverTo": ["applicant", "buyer"]
      },
      {
        "contactsType": "returnSampleTo",
        "deliverOthers": "retest@.com",
        "deliverTo": ["applicant", "buyer"]
      }
    ],
    "invoiceDeliverWay": "Express-Freight Prepaid",
    "returnResidueSampleFlag": "0",
    "returnResidueSampleRemark": "Express-Freight Collect",
    "returnTestedSampleFlag": "1"
  },
  "dffList": [
    {
      "languageId": 1,
      "product": {
        "productDescription": "duckhahahhah",
        "lotNo": "1214",
        "refCode1": "89898989"
      },
      "productSamples": [
        {
          "sampleID": "A",
          "otherSampleInformation": "666",
          "productDescription": "89898989"
        }
      ]
    },
    {
      "languageId": 2,
      "product": {
        "productDescription": "productDescription中文",
        "lotNo": "1214",
        "refCode1": "89898989"
      },
      "productSamples": [
        {
          "sampleID": "A",
          "otherSampleInformation": "666中文",
          "productDescription": "89898989中文"
        }
      ]
    }
  ]
}

// Enquiry请求参数模板
const defaultEnquiryRequestData = {
  "objectNo": "SZHL2506000666E",
  "objectType": "enquiry",
  "productLineCode": "HL",
  "applicant": {
    "contactName": "邬小姐applicant",
    "email": "zhangkerui@echom.com",
    "fax": "6666",
    "telephone": "+86 20 32200917",
    "mobile": "86 13544588122"
  },
  "payer": {
    "contactName": "张可锐payer",
    "email": "payerzhangkerui@echom.com",
    "fax": "payer444444",
    "telephone": "+86 20 32200918",
    "mobile": "666666"
  },
  "buyer": {
    "contactName": "张可锐buyer",
    "email": "zhangkerui@echom.com",
    "fax": "buyer444444",
    "telephone": "+86 20 32200916",
    "mobile": "333"
  },
  "agent": {
    "customerNameCn": "agentCustomerNameCn",
    "customerNameEn": "agentCustomerNameEn",
    "addressCn": "agentAddressCn",
    "addressEn": "agentAddressEn",
    "contactName": "agent张可锐",
    "email": "agentzhangkerui@echom.com",
    "fax": "agent444444",
    "telephone": "+86 20 32200919",
    "mobile": "111"
  },
  "supplier": {
    "customerNameCn": "supplierCustomerNameCn",
    "customerNameEn": "suppliercustomerNameEn",
    "addressCn": "supplieraddressCn",
    "addressEn": "supplieraddressEn",
    "contactName": "supplier张可锐",
    "email": "supplierzhangkerui@echom.com",
    "fax": "supplier87777",
    "telephone": "+86 20 32200917",
    "mobile": "5555"
  },
  "manufacturer": {
    "customerNameCn": "manufacturercustomerNameCn",
    "customerNameEn": "manufacturercustomerNameEn",
    "addressCn": "manufactureraddressCn",
    "addressEn": "manufactureraddressEn",
    "contactName": "manufacturer张可锐",
    "email": "manufacturerzhangkerui@echom.com",
    "fax": "manufacturer444444",
    "telephone": "+86 20 322009188",
    "mobile": "manufacturer333"
  },
  "reportInfo": {
    "sameAsApplicant": 0,
    "reportLanguage": "1",
    "reportHeaderEn": "GUANGZHOU XIYIN SUPPLY CHAIN MANAGEMENT CO., LTD8888",
    "reportHeaderCn": "广州希音供应链管理有限公司888ai",
    "reportAddressEn": "111111111111111111111111111111ai",
    "reportAddressCn": "广州市番禺区南村镇南草堂金坑广兴红棉路6号2栋102、201888888"
  },
  "serviceRequirement": {
    "contactInfos": [
      {
        "contactsType": "invoiceDeliverTo",
        "deliverOthers": "intest@.com",
        "deliverTo": ["applicant", "buyer"]
      },
      {
        "contactsType": "softCopyDeliverTo",
        "deliverOthers": "sftest@.com",
        "deliverTo": ["applicant", "buyer"]
      },
      {
        "contactsType": "returnSampleTo",
        "deliverOthers": "retest@.com",
        "deliverTo": ["applicant", "buyer"]
      }
    ],
    "invoiceDeliverWay": "Express-Freight Prepaid",
    "returnResidueSampleFlag": "0",
    "returnResidueSampleRemark": "Express-Freight Collect",
    "returnTestedSampleFlag": "1"
  },
  "dffList":[
        {
         "languageId":1,
         "product":{
            "productDescription":"kkkk",
            "lotNo":"1214",
            "refCode1":"89898989",
            "CountryOfOrigin":"United States",
            "CountryOfDestination":"United States"
         }
        }
    ]
}

// 状态管理
const loading = ref(false)
const requestData = ref(JSON.stringify(defaultOrderRequestData, null, 2))
const responseData = ref('')
const requestTime = ref('')
const responseTime = ref('')

// 获取当前测试类型的默认数据
const getCurrentDefaultData = () => {
  return formData.testType === 'order' ? defaultOrderRequestData : defaultEnquiryRequestData
}

// 重置请求参数
const resetRequestData = () => {
  const template = { ...getCurrentDefaultData() }
  template.objectNo = formData.orderNo
  requestData.value = JSON.stringify(template, null, 2)
  message.success('已重置为默认参数')
}

// 测试类型切换处理
const handleTestTypeChange = () => {
  const template = { ...getCurrentDefaultData() }
  template.objectNo = formData.orderNo
  requestData.value = JSON.stringify(template, null, 2)
  message.info(`已切换到${formData.testType === 'order' ? 'Order' : 'Enquiry'}更新测试模式`)
}

// 复制响应结果
const copyResponse = async () => {
  try {
    await navigator.clipboard.writeText(responseData.value)
    message.success('响应结果已复制到剪贴板')
  } catch (err) {
    message.error('复制失败')
  }
}

// 发送请求
const sendRequest = async () => {
  if (!formData.orderNo.trim()) {
    message.error('请输入订单号')
    return
  }

  try {
    // 验证JSON格式
    const parsedData = JSON.parse(requestData.value)
    parsedData.objectNo = formData.orderNo
    
    loading.value = true
    requestTime.value = new Date().toLocaleString()
    responseData.value = ''
    responseTime.value = ''

    const selectedEnv = environments.find(env => env.value === formData.environment)
    
    const response = await fetch(selectedEnv.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(parsedData)
    })

    responseTime.value = new Date().toLocaleString()
    
    const result = await response.text()
    
    if (response.ok) {
      try {
        // 尝试格式化JSON响应
        const jsonResult = JSON.parse(result)
        responseData.value = JSON.stringify(jsonResult, null, 2)
        message.success('请求成功')
      } catch {
        // 如果不是JSON格式，直接显示原始响应
        responseData.value = result
        message.success('请求成功')
      }
    } else {
      responseData.value = `HTTP ${response.status}: ${result}`
      message.error(`请求失败: ${response.status}`)
    }
    
  } catch (error) {
    responseTime.value = new Date().toLocaleString()
    if (error instanceof SyntaxError) {
      message.error('请求参数JSON格式错误')
      responseData.value = `JSON格式错误: ${error.message}`
    } else {
      message.error(`请求失败: ${error.message}`)
      responseData.value = `请求错误: ${error.message}`
    }
  } finally {
    loading.value = false
  }
}

// 监听订单号变化，自动更新请求参数中的objectNo
const updateObjectNo = () => {
  try {
    const parsedData = JSON.parse(requestData.value)
    parsedData.objectNo = formData.orderNo
    requestData.value = JSON.stringify(parsedData, null, 2)
  } catch (error) {
    // 如果JSON格式有误，不更新
  }
}
</script>

<template>
  <div class="order-update-test">
    <n-card title="更新API测试" :bordered="false">
      <n-space vertical size="large">
        <!-- 基本配置 -->
        <n-card title="基本配置" size="small" :bordered="true">
          <n-form :model="formData" label-placement="left" label-width="120px">
            <n-form-item label="测试类型" required>
              <n-radio-group v-model:value="formData.testType" @update:value="handleTestTypeChange">
                <n-space>
                  <n-radio 
                    v-for="type in testTypes" 
                    :key="type.value" 
                    :value="type.value"
                  >
                    {{ type.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item :label="formData.testType === 'order' ? '订单号' : 'Enquiry号'" required>
              <n-input 
                v-model:value="formData.orderNo" 
                :placeholder="formData.testType === 'order' ? '请输入订单号' : '请输入Enquiry号'"
                @blur="updateObjectNo"
                clearable
              />
            </n-form-item>
            <n-form-item label="测试环境">
              <n-radio-group v-model:value="formData.environment">
                <n-space>
                  <n-radio 
                    v-for="env in environments" 
                    :key="env.value" 
                    :value="env.value"
                  >
                    {{ env.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item label="请求地址">
              <n-input 
                :value="environments.find(env => env.value === formData.environment)?.url" 
                readonly
                type="textarea"
                :autosize="{ minRows: 1, maxRows: 2 }"
              />
            </n-form-item>
          </n-form>
        </n-card>

        <!-- 请求参数 -->
        <n-card title="请求参数" size="small" :bordered="true">
          <template #header-extra>
            <n-button @click="resetRequestData" size="small" type="primary" ghost>
              <template #icon>
                <n-icon><Refresh /></n-icon>
              </template>
              重置参数
            </n-button>
          </template>
          <n-input
            v-model:value="requestData"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 20 }"
            placeholder="请求参数JSON"
            show-count
          />
          <n-space justify="end" style="margin-top: 12px;">
            <n-button 
              @click="sendRequest" 
              type="primary" 
              :loading="loading"
              :disabled="!formData.orderNo.trim()"
            >
              <template #icon>
                <n-icon><Send /></n-icon>
              </template>
              发送请求
            </n-button>
          </n-space>
        </n-card>

        <!-- 响应结果 -->
        <n-card title="响应结果" size="small" :bordered="true" v-if="responseData || loading">
          <template #header-extra>
            <n-space>
              <n-text depth="3" v-if="requestTime">
                请求时间: {{ requestTime }}
              </n-text>
              <n-text depth="3" v-if="responseTime">
                响应时间: {{ responseTime }}
              </n-text>
              <n-button 
                @click="copyResponse" 
                size="small" 
                type="primary" 
                ghost
                v-if="responseData"
              >
                <template #icon>
                  <n-icon><Copy /></n-icon>
                </template>
                复制结果
              </n-button>
            </n-space>
          </template>
          
          <n-spin :show="loading">
            <n-input
              v-model:value="responseData"
              type="textarea"
              :autosize="{ minRows: 8, maxRows: 25 }"
              readonly
              placeholder="响应结果将显示在这里..."
              show-count
            />
          </n-spin>
        </n-card>
      </n-space>
    </n-card>
  </div>
</template>

<style scoped>
.order-update-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.n-card {
  margin-bottom: 16px;
}

.n-input[readonly] {
  background-color: var(--n-color-disabled);
}
</style>